package com.mairuide.phone.callanalysis.service;

import com.mairuide._frame.base.BaseRepository;
import com.mairuide._frame.base.BaseServiceProxy;
import com.mairuide.entity.PageResult;
import com.mairuide.phone.PhoneRecord;
import com.mairuide.phone.callanalysis.dao.CallAnalysisRepository;
import org.apache.commons.lang3.StringUtils;
import org.hibernate.SQLQuery;
import org.hibernate.transform.Transformers;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.jpa.domain.Specification;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.criteria.*;
import java.util.*;
import java.util.stream.Collectors;

/**
 * Created by 敲代码的卡卡罗特
 * on 2018/12/17 12:19.
 */
@Service
public class CallAnalysisD3Service extends BaseServiceProxy<PhoneRecord> {

    @Autowired
    private CallAnalysisRepository callAnalysisRepository;
    @Autowired
    private CallAnalysisService callAnalysisService;

    @PersistenceContext
    private EntityManager entityManager;
    @Autowired
    private JdbcTemplate jdbcTemplate;

    @Override
    protected EntityManager getEntityManager() {
        return entityManager;
    }

    @Override
    protected BaseRepository<PhoneRecord> getBaseRepository() {
        return callAnalysisRepository;
    }

    public Map detail(Map<String,String> whereMap) {
        StringBuffer sb=new StringBuffer();
        sb.append(" select * FROM (SELECT SERVICE_NUMBER ,PARTY_NUMBER ,count(1) AS count  ");
        sb.append(" from TB_PHONE_RECORDING WHERE 1=1 ");
        if (StringUtils.isNotBlank(whereMap.get("CASEMANAGE_ID"))){ // 案件id
            sb.append(" and  CASEMANAGE_ID = '" + whereMap.get("CASEMANAGE_ID")+"'");
        }
        if (whereMap.get("CALL_TYPE")!=null&&StringUtils.isNotBlank(String.valueOf(whereMap.get("CALL_TYPE")))){ // 呼叫类型
            sb.append(" and CALL_TYPE = " +String.valueOf(whereMap.get("CALL_TYPE"))+"");
        }
        if (StringUtils.isNotBlank(whereMap.get("SERVICE_USER_INFORMATION"))){ // 对方姓名
            sb.append(" and SERVICE_USER_INFORMATION = '" + whereMap.get("SERVICE_USER_INFORMATION")+"'");
        }
        if (StringUtils.isNotBlank(whereMap.get("PARTY_NUMBER"))){ // 对方号码
            sb.append(" and PARTY_NUMBER = '" + whereMap.get("PARTY_NUMBER")+"'");
        }
        if (StringUtils.isNotBlank(whereMap.get("PARTY_LOCATION"))){ // 对方号码归属地
            sb.append(" and PARTY_LOCATION like '%" + whereMap.get("PARTY_LOCATION")+"%'");
        }
        if (StringUtils.isNotBlank(whereMap.get("begin_time"))){ // 开始时间
            sb.append(" and  to_char(STARTING_TIME,'yyyy-mm-dd') >= '" + whereMap.get("begin_time")+"'");
        }
        if (StringUtils.isNotBlank(whereMap.get("end_time"))){ // 结束时间
            sb.append(" and  to_char(STARTING_TIME,'yyyy-mm-dd') <= '" + whereMap.get("end_time")+"'");
        }
        if (StringUtils.isNotBlank(whereMap.get("SERVICE_NUMBER"))){ // 电话号码集合
            sb.append(" and SERVICE_NUMBER in (" + whereMap.get("SERVICE_NUMBER")+")");
        } else {
            sb.append("and 1=0 ");
        }
        sb.append(" GROUP BY  SERVICE_NUMBER,PARTY_NUMBER,PARTY_LOCATION) p where 1=1 ");
        if(StringUtils.isNotBlank(whereMap.get("FREQUENCY_COUNT"))){ //次数
            sb.append(" and p.count >= " + whereMap.get("FREQUENCY_COUNT"));
        }
        List<Map<String, Object>> maps = jdbcTemplate.queryForList(sb.toString());

        //d3 数据整理
        Map<String, Object> hashMap = new HashMap<>();
        if(maps.size()>0){
            List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
            Set<Object> set_SERVICE_NUMBER = maps.stream().map(m -> m.get("SERVICE_NUMBER")).collect(Collectors.toSet());
            String cardList = whereMap.get("SERVICE_NUMBER");
            String[] split = cardList.split(",");
            List<String> collect = Arrays.asList(split);
            for (String s:collect){
                if(set_SERVICE_NUMBER.contains(s)){
                    HashMap<String, Object> node_map = new HashMap<>();
                    node_map.put("id",UUID.randomUUID().toString());
                    node_map.put("name",s);
                    node_map.put("width",100);
                    node_map.put("height",100);
                    node_map.put("image","/plugins/d3/image/body1.png");
                    nodes.add(node_map);
                }
            }
            for(int i=0;i<maps.size();i++){
                List<String> phone_list = nodes.stream().map(m ->(String) m.get("name")).collect(Collectors.toList());
                if (!phone_list.contains(maps.get(i).get("PARTY_NUMBER").toString())){
                    HashMap<String, Object> node_map = new HashMap<>();
                    node_map.put("id",UUID.randomUUID().toString());
                    node_map.put("name",maps.get(i).get("PARTY_NUMBER").toString());
                    node_map.put("width",60);
                    node_map.put("height",60);
                    node_map.put("image","/plugins/d3/image/ka1.png");
                    nodes.add(node_map);
                }
            }

            //linke 连线规则
            for (int i=0;i<maps.size();i++){
                Map<String, Object> stringObjectMap = maps.get(i);
                HashMap<String, Object> links_map = new HashMap<>();
                String SERVICE_NUMBER = (String)stringObjectMap.get("SERVICE_NUMBER");
                String PARTY_NUMBER = (String)stringObjectMap.get("PARTY_NUMBER");
                for (Map<String, Object> m:nodes){
                    if (SERVICE_NUMBER.equals((String)m.get("name"))){
                        links_map.put("node1",m.get("id"));
                    }
                    if (PARTY_NUMBER.equals((String)m.get("name"))){
                        links_map.put("node2",m.get("id"));
                    }
                    links_map.put("name","通话了"+stringObjectMap.get("COUNT")+"次");
                }
                if(!links_map.keySet().contains("node1")||!links_map.keySet().contains("node2")) continue;
                links.add(links_map);
            }
            hashMap.put("links",links);
            hashMap.put("nodes",nodes);
        }
        return hashMap;
    }

    /**
     * 共同联系人的d3
     *
     * @param whereMap
     * @return
     */
    public Map commonContactsPeople_D3(Map<String,String> whereMap) {
        HashMap<String, Object> maps = callAnalysisService.commonContactsPeople(whereMap);
        List<Map<String, Object>> body = (List<Map<String, Object>>)maps.get("body");
        body.remove(body.size()-1);//移除掉最后一个的值
        ArrayList<Map<String, Object>> list = new ArrayList<>();
        for (int i=0;i<body.size();i++){
            Map<String, Object> stringObjectMap = body.get(i);
            List<Map<String, Object>> body1 =(List<Map<String, Object>>) stringObjectMap.get("body");
            list.addAll(body1);
        }

        //d3 数据整理
        Map<String, Object> hashMap = new HashMap<>();
        if(list.size()>0){
            List<Map<String, Object>> nodes = new ArrayList<Map<String, Object>>();
            List<Map<String, Object>> links = new ArrayList<Map<String, Object>>();
            Set<Object> set_SERVICE_NUMBER = list.stream().filter(m->m!=null).map(m -> m.get("SERVICE_NUMBER")).collect(Collectors.toSet());
            String cardList = whereMap.get("SERVICE_NUMBER");
            String[] split = cardList.split(",");
            List<String> collect = Arrays.asList(split);
            for (String s:collect){
                if(set_SERVICE_NUMBER.contains(s)){
                    HashMap<String, Object> node_map = new HashMap<>();
                    node_map.put("id",UUID.randomUUID().toString());
                    node_map.put("name",s);
                    node_map.put("width",100);
                    node_map.put("height",100);
                    node_map.put("image","/plugins/d3/image/body1.png");
                    nodes.add(node_map);
                }
            }
            for(int i=0;i<list.size();i++){
                List<String> phone_list = nodes.stream().map(m ->(String) m.get("name")).collect(Collectors.toList());
                if (list.get(i)!=null&&!phone_list.contains(list.get(i).get("PARTY_NUMBER").toString())){
                    HashMap<String, Object> node_map = new HashMap<>();
                    node_map.put("id",UUID.randomUUID().toString());
                    node_map.put("name",list.get(i).get("PARTY_NUMBER").toString());
                    node_map.put("width",60);
                    node_map.put("height",60);
                    node_map.put("image","/plugins/d3/image/ka1.png");
                    nodes.add(node_map);
                }
            }

            //linke 连线规则
            for (int i=0;i<list.size();i++){
                Map<String, Object> stringObjectMap = list.get(i);
                if (stringObjectMap==null) continue;
                HashMap<String, Object> links_map = new HashMap<>();
                String SERVICE_NUMBER = (String)stringObjectMap.get("SERVICE_NUMBER");
                String PARTY_NUMBER = (String)stringObjectMap.get("PARTY_NUMBER");
                for (Map<String, Object> m:nodes){
                    if (SERVICE_NUMBER.equals((String)m.get("name"))){
                        links_map.put("node1",m.get("id"));
                    }
                    if (PARTY_NUMBER.equals((String)m.get("name"))){
                        links_map.put("node2",m.get("id"));
                    }
                    links_map.put("name","通话了"+stringObjectMap.get("COUNT")+"次");
                }
                if(!links_map.keySet().contains("node1")||!links_map.keySet().contains("node2")) continue;
                links.add(links_map);
            }
            hashMap.put("links",links);
            hashMap.put("nodes",nodes);
        }
        return hashMap;
    }
}
